package com.example.processor

import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.KSAnnotated


private class CrudProcessor(
    private val codeGenerator: CodeGenerator,
    private val logger: KSPLogger,
    private val configs: List<CrudDsl.EntityConfig>, // 支持多个配置
) : SymbolProcessor {

    override fun process(resolver: Resolver): List<KSAnnotated> {
        configs.forEach { config ->
            // 直接生成代码，不验证类是否存在
            generateCrudMethods(config)
        }
        return emptyList()
    }

    private fun generateCrudMethods(config: CrudDsl.EntityConfig) {
        val packageName = config.className.substringBeforeLast('.')
        val simpleName = config.className.substringAfterLast('.')

        val file = codeGenerator.createNewFile(
            dependencies = Dependencies(false),
            packageName = packageName,
            fileName = "${simpleName}Module" // 使用正确的控制器类名
        )

        file.write(
            """
            package $packageName
            
            import org.springframework.web.bind.annotation.*
            import org.opsli.core.base.entity.BaseEntity
            import com.baomidou.mybatisplus.core.mapper.BaseMapper
            import org.apache.ibatis.annotations.Mapper
            import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
            import org.springframework.stereotype.Service
            import io.swagger.annotations.Api
            import io.swagger.annotations.ApiOperation
            import org.opsli.api.base.result.ResultWrapper
            import org.opsli.common.annotation.ApiRestController
            
            class $simpleName : BaseEntity() {
            
            }
            
            @Mapper
            interface ${simpleName}Mapper : BaseMapper<$simpleName>
            
            @Service
            open class ${simpleName}Service : ServiceImpl<${simpleName}Mapper, ${simpleName}>()

            
            @Api(tags = ["${config.apiTag}"])
            @ApiRestController("/{ver}/${config.basePath}")
            open class ${simpleName}Controller(
                override val service: ${simpleName}Service,
            ) : JsonQueryController<${simpleName}, ${simpleName}Mapper, ${simpleName}Service> {
                override fun getEntityClass(): Class<${simpleName}> = ${simpleName}::class.java
            }
            
            """.trimIndent().toByteArray()
        )
        file.close()
    }
}

class ConfigCrudProcessorProvider : SymbolProcessorProvider {
    override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor {
        val crudConfig = crudConfig {
            entity("org.opsli.modulars.aryv.maproutefavorite.MapRouteFavorite") {
                apiTag = "路线收藏"
            }
        }
        return CrudProcessor(environment.codeGenerator, environment.logger, crudConfig)
    }
}